<?php

class ValidatorEngine
{
	const QUERY_STRING = 0;
	const DATA = 2;
	const COOKIE = 4;
	
	private $_unsafeInputs;	
	private $_safeInputs;
	
	public $settings;
	
	function __construct ( $settings = NULL ) 
	{		
		$this->settings = $settings == NULL ? new ValidatorSettings() : $settings;
		$this->_unsafeInputs = array();
		$this->_safeInputs = array();
	}

	public function expectedInput( $variableName, IValidator $validator = NULL, $type = ValidatorEngine::QUERY_STRING )
	{
		$this->_unsafeInputs[ $variableName ] = array ( $validator, $type );
	}
	
	public function validate()
	{
		global $_insecureGET, $_insecurePOST, $_insecureCOOKIE;		
		
		foreach( $this->_unsafeInputs as $variableName => $context )
		{
			$validator = $context[ 0 ];
			$type = $context[ 1 ];
			
			switch( $type )
			{
				case ValidatorEngine::QUERY_STRING:	
					$this->_doValidate( $_insecureGET, $variableName, $validator);
					break;		
				case ValidatorEngine::DATA:	
					$this->_doValidate( $_insecurePOST, $variableName, $validator);
					break;		
				case ValidatorEngine::COOKIE:	
					$this->_doValidate( $_insecureCOOKIE, $variableName, $validator);
					break;		
			}
		}
	}
	
	public function getParameter( $variableName )
	{
		$value = NULL;
		if ( isset( $this->_safeInputs[ $variableName ] ) )
		{
			$value = $this->_safeInputs[ $variableName ];
		}
		return $value;
	}
	
	private function _doValidate( $insecureVariables, $variableName, $validator )
	{
		if ( isset( $insecureVariables[ $variableName ] ) )
		{
			$unsafeInput = $insecureVariables[ $variableName ];
			
			if ( $validator != NULL )
			{
				$safeValue = $validator->Validate( $unsafeInput );
						
				if ( $safeValue != NULL )
				{
					$this->_safeInputs[ $variableName ] = $safeValue;
				}
				elseif ( $this->settings->throwExceptionOnValidationFailed )
				{
					throw new ValidationException("Validation Exception");
				}
			}
			elseif ( $this->settings->nullValidatorAreSafe )
			{
				$this->_safeInputs[ $variableName ] = $unsafeInput ;
			}
		}	
	}
}

?>